<template>
  <div>
    <el-drawer
      custom-class="wxkj-drawer content-management-edit-drawer"
      :title="drawerTitle"
      :visible.sync="drawerShow"
      size="500px"
    >
      <div class="drawer-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item v-show="false" label="id：" prop="id">
            <el-input v-model="form.id" />
          </el-form-item>
          <!-- <el-form-item v-show="false" label="thumb：" prop="thumb">
            <el-input v-model="form.thumb" />
          </el-form-item> -->
          <el-form-item label="标题：" required prop="title">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="发布日期：" prop="publishTime">
            <el-date-picker
              v-model="form.publishTime"
              type="datetime"
              style="width: 100%;"
              placeholder="选择日期时间"
            />
          </el-form-item>
          <el-form-item label="缩略图：" prop="thumb">
            <upload-cropper
              ref="uploadCropper"
              class="wrap"
              :style="{height:(310/(bannerWidth/bannerHeight))+'px' ,lineHeight:(310/(bannerWidth/bannerHeight))+'px'}"
              :enlarge="2"
              :init-img="thumb_dictText"
              :auto-crop-width="bannerWidth"
              :tip-content="'只支持JPG格式,建议使用大小不要超过1000k、'+bannerWidth+'*'+bannerHeight+'像素的图片'"
              :fixed-number="[bannerWidth,bannerHeight]"
              @upload="getUploadImgId"
            />
          </el-form-item>
          <el-form-item label="内容："  prop="content">
            <tinymce-editor ref="editor" v-model="form.content" :height="250" />
          </el-form-item>

          <el-form-item label="相关附件：">
            <uploadFile ref="uploadFile" :initName="form.attachment_fileRealName" :initUrl="form.attachment_url" @upload="uploadFile"/>
          </el-form-item>
          <div class="drawer-form-buttom-group">
            <el-button type="primary" :loading="waiting[1]" @click.native="submit('form',1)">发布</el-button>
            <el-button type="primary" :loading="waiting[0]" @click.native="submit('form',0)">草稿</el-button>
            <el-button @click="drawerClose">取消</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import tinymceEditor from '@/components/Tinymce'
import uploadCropper from '@/components/uploadCropper'
import uploadFile from '@/components/uploadFile'
import { cmsContent_add, cmsContent_edit, cmsContent_queryById } from '@/api/article'

export default {
  components: { tinymceEditor, uploadCropper,uploadFile },

  data() {
    var validateUploadImg = (rule, value, callback) => {
      if (value === '') {
        this.$refs.uploadCropper.uploadError(true)
        callback(new Error('请上传图片'))
      }
      callback()
    }

    return {
      drawerShow: false,
      drawerTitle: '',
      thumb_dictText: '', // 展示缩略图使用
      form: {
        'title': '',
        'content': '',
        'thumb': '',
        'channelId': '',
        'publishTime': '',
        'attachment': '',
        'attachment_fileRealName': '',
        'attachment_url': '',
      },
      //  imageUrl: '',
      rules: {
        title: [
          { required: true, message: '请填写标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        publishTime: [
          { required: true, message: '请选择发布时间', trigger: 'blur' }
        ],
        thumb: [
          { required: true, message: '请上传图片' },
          { validator: validateUploadImg }
        ],
        content: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ]
      },
      bannerWidth: 0,
      bannerHeight: 0,
      waiting: [false, false]
    }
  },
  watch: {
    drawerShow(bl) {
      if (!bl) {
        this.thumb_dictText = ''
        this.form.content = ''
        this.$refs.uploadFile.init();
        this.$refs.form.resetFields()
        this.form = {
        'title': '',
        'content': '',
        'thumb': '',
        'channelId': '',
        'publishTime': '',
        'attachment': '',
        'attachment_fileRealName': '',
        'attachment_url': '',
      };
        this.$refs.editor.setContent('')
        this.$refs.uploadCropper.initUpload()
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  // 销毁
  destroyed() {
  },
  // 方法
  methods: {
    uploadFile(res){
      this.form.attachment = res.fileId;
    },
    // 关闭弹窗
    drawerClose() {
      this.drawerShow = false
      this.$emit('refresh')
    },
    show(title, bannerWidth, bannerHeight, id, channelId) {
      this.drawerTitle = title
      this.drawerShow = true
      this.form.id = id
      this.form.channelId = channelId
      this.bannerWidth = bannerWidth
      this.bannerHeight = bannerHeight
      // 编辑传参
      // this.drawerShow = false
      try {
        if (id) { // 编辑
          cmsContent_queryById({ id }).then(response => {
            const data = response.result
            this.thumb_dictText = data.thumb_dictText// 为了展示图片，且不影响提交
            Object.keys(this.form).forEach(k => { // 仅保留需要修改的对象
              this.form[k] = data[k]
            })
            this.form.attachment = data.attachment;
            this.form.attachment_fileRealName = data.attachment_fileRealName;
            this.form.attachment_url = data.attachment_url;
            this.form.publishTime = new Date(this.form.publishTime)
            this.$refs.editor.setContent(this.form.content)
          })
        } else {
          console.log('新增情况下  ')
          // . this.form.publishTime=new Date();//日期插件默认当前日期
        }
        console.log("form::::",this.form);
      } catch (e) {
        // TODO handle the exception
      }
    },

    // 保存
    submit(form, publishStatus) {
      console.log(this.form)
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.waiting[publishStatus] = true
          this.form.publishStatus = publishStatus
          if (this.form.id) { // 编辑
            cmsContent_edit(this.form).then(response => {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.drawerShow = false
              this.waiting[publishStatus] = false
              this.$emit('refresh')
            }).catch(() => {
              this.waiting[publishStatus] = false
            })
          } else {
            cmsContent_add(this.form).then(response => {
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
              this.drawerShow = false
              this.waiting[publishStatus] = false
              this.$emit('refresh')
            }).catch(() => {
              this.waiting[publishStatus] = false
            })
          }
        }
      })
    },

    // 图片id
    getUploadImgId(id) {
      this.form.thumb = id
      this.$refs.form.clearValidate('thumb')
    }
  }
}
</script>
<style lang="scss">
  .content-management-edit-drawer {
    .drawer-content {
      padding: 20px;
    }
  }
  .wrap{
    width: 100%;
    div{width: 100%;height: 100%;line-height:inherit;}
  }
</style>
